const canvas = document.getElementById("canvas");
const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
const sizeEL = document.getElementById("size");
const colorEl = document.getElementById("color");
const clearEl = document.getElementById("clear");

// 3.1 getContext()方法 ->返回 canvas 的上下文...
const ctx = canvas.getContext("2d"); // "2d": 建立二维渲染上下文

let size = 10; // 默认绘画粗细大小
let isPressed = false;
colorEl.value = "black";
let color = colorEl.value; // 默认颜色为黑色
let x;
let y;

// 3.2 鼠标按下
canvas.addEventListener("mousedown", (e) => {
  isPressed = true; // 标记当前(鼠标)已经按下

  x = e.offsetX;
  y = e.offsetY;
});

// 3.3 鼠标抬起
document.addEventListener("mouseup", (e) => {
  isPressed = false;

  x = undefined;
  y = undefined;
});

// 3.4 鼠标来回移动
canvas.addEventListener("mousemove", (e) => {
  if (isPressed) {
    const x2 = e.offsetX;
    const y2 = e.offsetY;

    drawCircle(x2, y2);
    drawLine(x, y, x2, y2);

    x = x2;
    y = y2;
  }
});

// 3.4同步1: 线的组成, 是以多个 “圆线” 进行组成的！！！(自己模拟)
function drawCircle(x, y) {
  ctx.beginPath(); // 3.4.1 开始绘制路径
  ctx.arc(x, y, size, 0, Math.PI * 2);
  ctx.fillStyle = color; // 3.4.2 填充颜色(默认黑色)
  ctx.fill();
}

// 3.4同步2: 绘制线
function drawLine(x1, y1, x2, y2) {
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.strokeStyle = color;
  ctx.lineWidth = size * 2;
  ctx.stroke();
}

function updateSizeOnScreen() {
  sizeEL.innerText = size;
}

increaseBtn.addEventListener("click", () => {
  size += 5;

  if (size > 50) {
    size = 50;
  }

  updateSizeOnScreen();
});

decreaseBtn.addEventListener("click", () => {
  size -= 5;

  if (size < 5) {
    size = 5;
  }

  updateSizeOnScreen();
});

colorEl.addEventListener("change", (e) => (color = e.target.value));

clearEl.addEventListener("click", () =>
  ctx.clearRect(0, 0, canvas.width, canvas.height)
);
